<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>产品工序设计</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link rel="stylesheet" href="../../../lib/layui-v2.5.5/css/layui.css" media="all">
		<link rel="stylesheet" href="../../../css/layuicmspublic.css" media="all">
		<link rel="stylesheet" href="../../../css/public.css" media="all">
		<link rel="stylesheet" href="../../../js/bootstrap/css/bootstrap.min.css" media="all">

		<!-- <link rel="stylesheet" type="text/css" href="https://raw.githack.com/hnzzmsf/layui-formSelects/master/dist/formSelects-v4.css" /> -->
	</head>

	<body>
		<div style="display: none;" type="text/html" id="loadProDetailsTableBar">
			<a class="layui-btn goods_btn_update layui-btn-xs layui-btn-warm data-count-delete" lay-event="designs">设计</a>
		</div>


		<!--表格结束-->
		<div id="yby">

			<form method="post" class="layui-form layui-form-pane" lay-filter="dataFrm" id="dataFrm">
				<div class="layui-col-md12 layui-col-xs12">
					<div class="layui-row ">

						<div class="layui-inline">
							<div class="layui-form-item magt3">
								<label class="layui-form-label">工序单编号：</label>
								<div class="layui-input-block">
									<input type="text" name="designId" id="designId" disabled="disabled" class="layui-input" lay-verify="required"
									 placeholder="工序单编号">
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">产品名称：</label>
								<div class="layui-input-block">
									<!-- 做修改  -->
									<input type="hidden" name="id" />
									<input type="text" name="productName" disabled="disabled" class="layui-input" lay-verify="required"
									 placeholder="产品名称">
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">设计人：</label>
								<div class="layui-input-block">
									<input type="text" name="register" disabled="disabled" class="layui-input" lay-verify="required" placeholder="设计人">
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">产品编号：</label>
								<div class="layui-input-block">
									<input type="text" name="productId" disabled="disabled" class="layui-input" lay-verify="required" placeholder="产品编号">
								</div>
							</div>
							<!--  -->
							<div class="layui-inline">
								<label class="layui-form-label">物料总成本：</label>
								<div class="layui-input-block">
									<input type="text" name="moduleSubtotal" id="moduleSubtotal" value="0" disabled="disabled" class="layui-input"
									 lay-verify="required" placeholder="物料总成本">



								</div>
							</div>

							<!--表格开始-->
							<table class="layui-hide" id="loadProDetailsTable" style="margin-top: 10px;" lay-filter="loadProDetailsTable"></table>


							<div class="layui-inline">
								<label class="layui-form-label">审核人：</label>
								<div class="layui-input-block">
									<input type="text" name="checker" value="0" class="layui-input" lay-verify="required" placeholder="审核人">
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">审核时间：</label>
								<div class="layui-input-block">
									<input type="text" name="checkTime" value="0" class="layui-input" lay-verify="required" placeholder="审核时间">
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">工时总成本：</label>
								<div class="layui-input-block">
									<input type="text" name="costPriceSum" value="0" class="layui-input" lay-verify="required" placeholder="工时总成本">
								</div>
							</div>

							<div class="layui-form-item magt3">
								<label class="layui-form-label">设计要求：</label>
								<div class="layui-input-block">
									<!-- 	<input type="text" name="procedureDescribe" value="0"  class="layui-input" lay-verify="required"
								 placeholder="设计要求"> -->

									<textarea placeholder="设计要求" name="procedureDescribe" style="margin: 0px; height: 212px; width: 765px;"></textarea>

								</div>
							</div>




						</div>
					</div>

				</div>
				<div class="layui-form-item">
					<div class="" style="text-align: center;padding-top: 20px;">
						<a class="layui-btn " lay-submit="" lay-filter="doSubmit"><label class="layui-icon layui-icon-release"></label>提交</a>
						<!-- <a class="layui-btn layui-btn-warm" onclick="javascript:$('#dataFrm')[0].reset()" lay-filter="data-search-btn"><label
												 class="layui-icon layui-icon-refresh"></label>重置</a> -->
						<a class="layui-btn layui-btn-warm" href="javascript:(window.location.href='AssignWorkOrderForProduction.html');"
						 lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>返回上一级</a>
					</div>
				</div>
			</form>
			<!--添加和修改的弹出层开始-->
			<div id="addOrUpdateDiv" style="display: none;padding: 1.3125rem 3.3125rem 0.3125rem 3.3125rem;">

				<form method="post" class="layui-form layui-form-pane" lay-filter="dataFrm2" id="dataFrm2">
					<div class="layui-col-md12 layui-col-xs12">
						<div class="layui-row ">
							<div class="layui-inline">

								<!-- <input type="hidden" name="id" /> -->

								<div class="layui-form-item magt3">
									<label class="layui-form-label">工序编号：</label>
									<div class="layui-input-block">
										<input type="text" name="id" disabled="disabled" id="id" class="layui-input" lay-verify="required"
										 placeholder="工序单编号">
									</div>
								</div>
								<div class="layui-inline">
									<label class="layui-form-label">工序名称：</label>
									<div class="layui-input-block">
										<input type="text" name="procedureName" id="procedureName" disabled="disabled" class="layui-input" lay-verify="required"
										 placeholder="工序名称">
									</div>
								</div>
								<div class="layui-inline">
									<label class="layui-form-label">产品编号：</label>
									<div class="layui-input-block">
										<input type="text" name="productId" id="productId" disabled="disabled" class="layui-input" lay-verify="required"
										 placeholder="产品编号">
									</div>
								</div>

							</div>


							<!--表格开始-->
							<table class="layui-hide" id="loadProDetailsTable2" style="margin-top: 10px;" lay-filter="loadProDetailsTable2"></table>




							<div class="layui-form-item">
								<div class="" style="text-align: center;padding-top: 20px;">
									<a class="layui-btn " lay-submit="" lay-filter="doSubmit2"><label class="layui-icon layui-icon-release"></label>提交</a>
									<!-- <a class="layui-btn layui-btn-warm" href="javascript:(AssignWorkOrderForProduction.html);" lay-filter="data-search-btn"><label
													 class="layui-icon layui-icon-refresh"></label>返回上一级</a> -->
								</div>
							</div>
				</form>


			</div>
		</div>
		<!--添加和修改的弹出层结束-->


		</div>
		</div>
		<!-- </div> -->
		<!-- </div> -->
		<script src="../../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
		<script src="../../../lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
		<script src="../../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
		<script src="../../../lib/jq-module/jquery.particleground.min.js" charset="utf-8"></script>
		<script src="../../../lib/common/jquery.cookie.min.js" charset="utf-8"></script>
		<script src="../../../lib/common/common.js" charset="utf-8"></script>
		<script src="../../../js/vue/vuejs-2.5.16.js" charset="utf-8"></script>
		<script src="../../../js/vue/vue-selected.js" charset="utf-8"></script>
		<script src="../../../js/vue/axios-0.18.0.js" charset="utf-8"></script>
		<script type="text/javascript">
			Vue.component('v-select', VueSelect.VueSelect);
			new Vue({
				el: '#yby',
				data: {
					id: "",
					placeholder: '可以进行多选',
					processOptions: [],
					selectBrands: [],
					sel_brand_obj: [],
				},
				methods: {
					selected_brand: function(values) {
						// this.selectBrands =values.map(function(obj){
						//     return obj.id
						// });
						// console.log(this.sel_brand_obj)
					},
					loadProcessOptions: function() {
						var _this = this
						axios.post(api1 + "PDetails/findAll", {}, {
								headers: {
									'TOKEN': token
								}
							})
							.then(function(response) {
								// alert("Sdsdsd")
								// console.log(response.data)
								_this.processOptions = response.data;
								// console.log("----------------------" + _this.processOptions)
							}).catch(function(reason) {
								// console.log(reason);
							})
					}
				},
				mounted() {
					this.loadProcessOptions()
				}
			})
		</script>
		<script>
			layui.use(['form', 'table', 'laydate', 'layer', 'upload'], function() {
				var form = layui.form;
				var table = layui.table;
				var laydate = layui.laydate;
				var layer = layui.layer;
				var upload = layui.upload;
				/* // 物料编号生成
				let id = generatingNumberingRules("201", 4)
				// console.log(id) */

				let rows = GetRequest();
				// console.log(rows)
				form.val("dataFrm", rows);

				var mainIndex;

				// 加载数据表格
				// /api1/ProcessMaterialDesign/loadProcesses
				// 定义 物料总合
				let moduleSubtotal = 0;
				// 定义 第二个设计 数据源
				let sheji = {};

				var tableIns = /* 第二层表格 */
					table.render({
						elem: '#loadProDetailsTable',
						url: api1 + 'ProcessMaterialDesign/loadProDetails?parentId=' + rows.id,
						// toolbar: "#goodsToolBar",
						cellMinWidth: true,
						//height: 'full-220',
						cols: [
							[{
									type: "checkbox",
									fixed: "left"
								},
								{
									field: 'detailsNumber',
									title: '序号',
									align: "center"
								},
								{
									field: 'procedureName',
									title: '工序名称',
									align: "center"
								},
								{
									field: 'procedureId',
									title: '工序编号',
									align: "center"
								},
								{
									field: 'procedureDescribe',
									title: '描述',
									align: "center"
								},
								{
									field: 'labourHourAmount',
									title: '小时数',
									align: "center"
								},
								{
									field: 'amountUnit',
									title: '工时单位',
									align: "center"
								},
								{
									field: 'subtotal',
									title: '工时成本小计',
									align: "center",
								},
								{
									field: 'moduleSubtotal',
									title: '物料成本小计',
									align: "center",
									templet:function(d){
										if(d.moduleSubtotal==''|| d.moduleSubtotal == null){
											return 0;
										}
										return d.moduleSubtotal;
									}
								},
								{
									title: '操作',
									// templet: '#loadProDetailsTableBar',
									fixed: "right",
									align: "center",
									templet: function(d) {
										if (d.moduleSubtotal !== '' || d.moduleSubtotal !== null) {
											return '<a class="layui-btn goods_btn_update layui-btn-xs layui-btn-warm data-count-delete" lay-event="designs">设计</a>';
										}
										return '<a  class="layui-btn goods_btn_update layui-btn-xs layui-btn-warm data-count-delete"  disabled="disabled" lay-event="designs">设计</a>';
									}
								}
							]
						],
						page: true,
						done: function(res, curr, count) {
							// tableIns.reload();
							console.log("llll", res)
							moduleSubtotal = 0;
							if (res.data.moduleSubtotal !== null || res.data.moduleSubtotal !== 'null') {
								$.each(res.data, function(index, val) {
									console.log(res.data);
									if(val.moduleSubtotal!==null && val.moduleSubtotal !== '' && val.moduleSubtotal!==NaN){
										moduleSubtotal += parseInt(val.moduleSubtotal);
									}else{
										console.log("有问题数据:",val.moduleSubtotal)
									}
									console.log(moduleSubtotal)
								})
								console.log("计算物料总数", moduleSubtotal)
								// 计算物料总数
								$("#moduleSubtotal").val((moduleSubtotal));
							}
						}
					});

				// 普通数字转会计金额格式 第一种
				function toThousandsFormates(num) {
					// 判断传进来的数字是否为非空数字
					if (!isNaN(parseFloat(num))) {
						var reg = /\./g
						var newNum = Number(Number(num).toFixed(2)).toLocaleString()
						// 判断转换后的数字是否带有小数
						if (reg.test(newNum)) {
							var numArr = newNum.split('.')
							// 判断小数点后数字长度为1，则自动补0
							numArr[1] = numArr[1].length === 1 ? numArr[1] + '0' : numArr[1]
							return numArr.join('.')
						} else {
							// 整数直接在后面补上0.00
							return newNum + '.00'
						}

					} else {
						return ''
					}
				}

				/* 
				ids=111&id=23&designId=201202007187200&firstKindId=01
				&firstKindName=电子&secondKindId=01&secondKindName=计算机
				&thirdKindId=01&thirdKindName=笔记本&productId=100010101000004
				&productName=联想拯救者&procedureDescribe=121212&
				costPriceSum=288&moduleCostPriceSum=3100&designer=admin&
				register=超级管理员&registerTime=2020-07-15 15:42:41&
				checker=超级管理员&checkTime=2020-07-18 14:46:16&
				checkSuggestion=null&checkTag=S001-2&changer=null&
				changeTime=null&changeTag=D002-1&designModuleTag=G002-1&
				designModuleChangeTag=G003-1 
				 */

				//监听行数据的事件
				table.on('tool(loadProDetailsTable)', function(obj) {
					var data = obj.data;
					console.log("设计loadProDetailsTable        ", data)
					console.log(rows)
					if (obj.event == "designs") {
						// let id = rows.id;
						let productName = rows.productName;
						let productId = rows.productId;
						// data.id = parseInt(id);
						data.productName = productName;
						data.productId = productId;
						// 渲染数据
						opendesigns(data);
					}

				});


				// 设计弹出 shadeClose 
				function opendesigns(data) {
					// console.log("设计弹出", data);
					mainIndex = layer.open({
						type: 1,
						title: '[' + rows.productName + ']设计工序数量',
						content: $("#addOrUpdateDiv"),
						area: ['80%', "650px"],
						id: 'ybyyaaaa',
						success: function(index) {
							//装载数据表格
							form.val("dataFrm2", data);
							/* 第二层表格 */
							table.render({
								elem: '#loadProDetailsTable2',
								url: api1 + 'ProcessMaterialDesign/loadProMaterial?productId=' + rows.productId,
								cellMinWidth: true,
								//height: 'full-220',
								cols: [
									[{
											type: "checkbox",
											fixed: "left"
										},
										{
											field: 'detailsNumber',
											title: '序号',
											align: "center",
										},
										{
											field: 'productName',
											title: '物料名称',
											align: "center"
										},
										{
											field: 'productId',
											title: '物料编号',
											align: "center"
										},
										{
											field: 'productDescribe',
											title: '描述',
											align: "center"
										},
										{
											field: 'amount',
											title: '设计数量',
											align: "center"
										},
										{
											field: 'residualAmount',
											title: '可用数量',
											align: "center"
										},
										{
											field: 'costPrice',
											title: '单价(元)',
											align: "center"
										},
										{
											field: 'subtotal',
											title: '小计',
											align: "center",

										},
										{
											field: 'bgamount',
											edit: 'bgamount',
											title: '本工序数量',
											align: "center",
										}
									]
								],
								page: true,
								done: function(res, curr, count) {
									sheji = res;
								}
							});
						}
					});

				}
				let sum = 0;
				// 定义每一行数据
				let submitData = [];
				//监听单元格编辑
				let fall = true;
				table.on('edit(loadProDetailsTable2)', function(obj) {

					/* var value = obj.value //得到修改后的值
						,
						data = obj.data //得到所在行所有键值
						,
						field = obj.field; //得到字段
					// console.log(value, data, field)
					layer.msg('[ID: ' + data.id + '] ' + field + ' 字段更改为：' + value); */
					//	// console.log("监听单元格数据",obj.tr[0].childNodes[9].childNodes[0].innerHTML = (obj.value * obj.data.costPrice));
					// 当前输入的数值
					let a = obj.value; // 1
					console.log("sum:", obj.value * obj.data.costPrice)
					console.log(sum)
					// 定义变量接收 当前监听的一行数据
					let data = obj.data;
					// 存储自己输入的数值
					data.amount = a;
					
					
					
					if(a > data.residualAmount){
						layer.msg('可用数量超出，请重新输入');
						return ;
					}
					
					// 幻觉
					obj.tr[0].childNodes[6].innerHTML = (data.residualAmount - a);
					obj.tr[0].childNodes[6].style.width = "100%";
					if (data.bgamount > data.residualAmount) {
						/* layer.msg('可用数量超出，请重新输入');
						obj.tr[0].childNodes[6].innerHTML = (0);
						obj.tr[0].childNodes[6].style.width = "100%"; */
						alert(1);
						// obj.tr[0].childNodes[9].innerHTML = (0);
						// obj.tr[0].childNodes[9].style.width = "100px";
						// obj.tr[0].childNodes[9].innerHTML = (data.bgamount - data.residualAmount);
						// data.bgamount = data.residualAmount;
						// obj.value = 0;
						// submitData.push(data);
						// layer.msg("数据全部清空")
					} else {
						
						if (data !== undefined) {
						// 1    2   --- 【1，2】
							if (a === '' && a.length <= 0) {
								// alert("进来啦");
								// 循环找到当前 相同的对象  如果有 则删除 没有则 添加
								for (var i = 0; i < submitData.length; i++) {
									let id = submitData[i].id;
									if (id == data.id) {
										console.log("aaaaaaaaaaaaaaaaaaaaaaaaaa", submitData[i])
										submitData.splice(i, 1);
									}
									
								}
							}else{
								// 添加
								submitData.push(data);
							}
						}
						layer.msg('[ID: ' + data.productName + '] 工序数量使用量：' + data.bgamount + "可用数量:" + data.residualAmount);
						console.log("集合数据查看/", submitData)
					}

				});



				//提交数据
				form.on("submit(doSubmit)", function(data) {
					// data.bgamount > data.residualAmount

					var btn = $(this);
					btn.text("提 交 中...").attr("disabled", "disabled").addClass("layui-disabled");
					var params = $("#dataFrm").serialize();

					/* 
					 moduleCostPriceSum: 
					 designId: 201202007200011
					 */
					console.log(params)
					let moduleCostPriceSum = $("#moduleSubtotal").val();
					let designId = $("#designId").val();


					$.post(api1 + "ProcessMaterialDesign/updatePPProcess?designId=" + designId + "&moduleCostPriceSum=" +
						moduleCostPriceSum,
						function(res) {
							layer.msg(res.msg);
							if (res.code == 200) {
								btn.text("提交").attr("disabled", "").removeClass("layui-disabled");
								tableIns.reload();
								// 跳转到 审核
								// 页面没有写
								window.location.href = "../ProcessMaterialDesignSheetReview/AssignWorkOrderForProduction.html"
							}
							layer.close(mainIndex);
						})
					return false;
				})


				/* 
				amount: "2"
				costPrice: 100
				detailsNumber: 1
				parentId: 36
				productDescribe: "不知道"
				productId: "100010101000009"
				productName: "手机壳"
				residualAmount: 77
				subtotal: 10000 
				 */

				//提交数据
				form.on("submit(doSubmit2)", function(data) {


					var btn = $(this);
					var params = $("#dataFrm2").serialize();

					// console.log(sheji)

					// console.log("设计", params);

					// 更新数据
					// let id = rows.id;
					// let moduleSubtotal = sum;

					// console.log("设计", id, moduleSubtotal);
					// console.log(data)
					// console.log(submitData)

					/* 
					 amount: "2"
					 costPrice: 100
					 detailsNumber: 1
					 parentId: 35
					 productDescribe: "不知道"
					 productId: "100010101000009"
					 productName: "手机壳"
					 residualAmount: 73
					 subtotal: 10000
					 
					 amount: 2
					 costPrice: 1000
					 detailsNumber: 2
					 parentId: 26
					 productDescribe: "ww"
					 productId: "100010101000002"
					 productName: "cpu"
					 residualAmount: 10
					 subtotal: 2000
					 */

					let da = {
						amount: 0,
						costPrice: 0,
						detailsNumber: 0,
						parentId: 0,
						productDescribe: "",
						productId: "",
						productName: "",
						residualAmount: 0,
						subtotal: 0
					}


					console.log($("#id").val())
					console.log("moduleSubtotal:", sum)
					console.log($("#procedureName").val())
					console.log($("#productId").val())

					/// ?id=" + parseInt(rows.id) + "&moduleSubtotal=" + sum

					let id = $("#id").val();
					let moduleSubtotal = sum;
					let procedureName = $("#procedureName").val();
					let productId = $("#productId").val();

					// let a = $('data-field="bgamount"');
					// console.log("aaaaaaaaaaaaaaaaaaa",a);
					console.log(submitData)

					for (var i = 0; i < submitData.length; i++) {
						console.log(submitData[i].bgamount, submitData[i].residualAmount)
						if (submitData[i].bgamount > submitData[i].residualAmount) {
							layer.msg("超出可用数量请重新设置...");
							return;
						}
						// 重新计算
						// sum += (obj.value * obj.data.costPrice);
						console.log(parseInt(submitData[i].bgamount), parseInt(submitData[i].costPrice))
						sum += parseInt(submitData[i].bgamount) * parseInt(submitData[i].costPrice);

					}

					console.log("重新计算", sum)





					$.post(api1 + "ProcessMaterialDesign/updateDetails?id=" + id + "&moduleSubtotal=" + sum,
						function(res) {
							layer.msg(res.msg);
							if (res.code == 200) {
								// 归零
								sum = 0;

								// 循环添加设计
								for (var i = 0; i < submitData.length; i++) {
									// 判断是否输入了工序数量 submitData bgamount
									console.log(submitData[i].bgamount)
									if (submitData[i].bgamount != "" || submitData[i].bgamount != null) {
										// console.log(rows);
										let productName = rows.productName;
										let productId = rows.productId;

										da.amount = parseInt(submitData[i].amount);
										da.costPrice = submitData[i].costPrice;
										da.detailsNumber = submitData[i].detailsNumber;
										da.parentId = parseInt(id);
										da.productDescribe = submitData[i].productDescribe;
										da.productId = submitData[i].productId;
										da.productName = submitData[i].productName;
										da.residualAmount = parseInt(submitData[i].residualAmount);
										da.subtotal = submitData[i].subtotal;
										// console.log(da)

										$.ajax({
											url: api1 + 'ProcessMaterialDesign/addProMater',
											data: da,
											type: 'POST',
											success(res) {
												if (res.code == 200) {
													layer.msg(res.msg);
												} else {
													layer.msg(res.msg);
												}
											},
											error(e) {
												console.log(e);
												// 清空当前表单所有数据
												submitData = [];
											}
										})
									}
								}
							}
							// 清空当前表单所有数据
							submitData = [];
							tableIns.reload();
							console.log("数据为:", submitData)
							layer.close(mainIndex);
						})

					layer.close(mainIndex);
					return false;
				})


			});
		</script>

		<!-- <script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js" type="text/javascript" charset="utf-8"></script>
	 
	<script src="https://raw.githack.com/hnzzmsf/layui-formSelects/master/dist/formSelects-v4.min.js" type="text/javascript" charset="utf-8"></script>
	 
	<script type="text/javascript">
	    //加载模块
	    layui.use(['jquery', 'formSelects'], function () {
	        var formSelects = layui.formSelects;
	   });
	</script> -->

	</body>

</html>
